import VueRouter from 'vue-router'
import Pages from "../views/Pages";

import testRouter from "./test";
import adminRouter from "./admin"
import contentRouter from "./content";
import loanRouter from "./loan";
import memberRouter from "./member";
import repaymentRouter from "./repayment";
import yunyingRouter from "./yuying";

const routes = [
    {
        path: "/login",
        name: "Login",
        component: () => import("../views/Login"),
        meta: {
            auth: true
        }
    },
    {
        path: "/noFound",
        name: "noFound",
        component: () => import("../views/noFound"),
        meta: {
            auth: true
        }
    },
    {
        path: "/",
        name: "Pages",
        component: Pages,
        children: [
            testRouter,
            adminRouter,
            contentRouter,
            loanRouter,
            memberRouter,
            repaymentRouter,
            yunyingRouter,
            {
                path: "/",
                name: "home",
                component: () => import("../views/repayment/home"),
                meta: {
                    auth: true
                }
            }
        ]
    }
]

const router = new VueRouter({
    mode: 'hash',
    base: process.env.BASE_URL,
    routes
})
//路由拦截（是否已经登录）

router.beforeEach((to, from, next) => {
    console.log("will to: ", to.fullPath)
    let user = JSON.parse(localStorage.getItem('user'));
    let spilts = to.path.split('/');
    let newArr = [];
    for (let i = 0; i < spilts.length; i++) {
        if (i < 3) {
            if (i == 2 && spilts[i] == '') {
                break;
            } else {
                newArr.push(spilts[i]);
            }
        }
    }
    let toPath = newArr.join('/')
    console.log(toPath)
    if (to.meta.auth == true || to.path == '/') {
        next();
    } else {
        if (user) {
            if ((user.userRoles.indexOf(toPath) > -1)) {
                next();
            } else {
                next({
                    path: '/noFound'
                })
            }
        } else {
            next({
                path: '/login'
            })
        }
    }
})
export default router
